package com.example.tobebigfe.utils

import java.io.*
import java.util.zip.ZipFile
import java.util.zip.ZipInputStream


object ZipUtils {

    fun unzip(input: InputStream, destFile: File) {
        val zis = ZipInputStream(input)
        while (true) {
            val entry = zis.nextEntry ?: break
            if (entry.isDirectory) {
                File(destFile, entry.name).mkdirs()
            } else {
                val outputFile = File(destFile, entry.name)
                if (!outputFile.exists()) {
                    val parentFile = outputFile.parentFile
                    if (!parentFile.exists()) {
                        parentFile.mkdirs()
                    }
                }
                val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
                val br = zis.buffered()
                val bw = FileOutputStream(outputFile)
                var length = 0
                while ({ length = br.read(buffer);length != -1 }()) {
                    bw.write(buffer, 0, length)
                }
                bw.flush()
            }
        }
    }

    fun unzip(sourceFile: File, destFile: File) {
        val zipFile = ZipFile(sourceFile)
        for (entry in zipFile.entries()) {
            if (entry.isDirectory) {
                File(destFile, entry.name).mkdirs()
            } else {
                val outputFile = File(destFile, entry.name)
                if (!outputFile.exists()) {
                    val parentFile = outputFile.parentFile
                    if (!parentFile.exists()) {
                        parentFile.mkdirs()
                    }
                }
                val input = zipFile.getInputStream(entry)
                input.use { input
                    outputFile.outputStream().use {
                        val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
                        val br = input.buffered()
                        val bw = it.buffered()
                        var length = 0
                        while ({ length = br.read(buffer);length != -1 }()) {
                            bw.write(buffer, 0, length)
                        }
                        bw.flush()
                    }
                }
            }
        }
    }

}